import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  Modal,
  DatePicker,
  Upload,
  Image,
  InputNumber,
  Tag,
  message,
} from 'antd';
import {
  BgColorsOutlined,
  PlusOutlined,
  TagsOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;

export default function GreenScreenTemplates() {
  const [form] = Form.useForm();
  const [data, setData] = useState(() => (
    Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      name: `绿幕-${i + 1}`,
      createBy: i % 2 === 0 ? 'admin' : 'designer',
      tagId: i % 3 === 0 ? 1 : 2,
      tagName: i % 3 === 0 ? '人物' : '风景',
      amount: Math.floor(Math.random() * 50) + 20,
      image: `https://picsum.photos/seed/green_${i}/240/160`,
      createTime: `2025-03-${(i % 28) + 1} 09:00:00`,
    }))
  ));
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [newOpen, setNewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [tagOpen, setTagOpen] = useState(false);
  const [tags, setTags] = useState([
    { id: 1, name: '人物' },
    { id: 2, name: '风景' },
    { id: 3, name: '生活' },
  ]);

  const columns = useMemo(() => ([
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 160 },
    { title: '创建者', dataIndex: 'createBy', width: 120 },
    {
      title: '绿幕图', dataIndex: 'image', width: 160,
      render: (url) => <Image src={url} width={120} height={80} style={{ objectFit: 'cover' }} />,
    },
    { title: '价格', dataIndex: 'amount', width: 100, render: (v) => (v ? `${v} 元` : '-') },
    { title: '标签', dataIndex: 'tagName', width: 120, render: (name) => <Tag>{name}</Tag> },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    {
      title: '操作', dataIndex: 'actions', fixed: 'right', align: 'right', width: 180,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(row)}>编辑</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>删除</Button>
        </Space>
      )
    },
  ]), []);

  const handleSearch = async () => {
    const values = await form.validateFields().catch(() => null);
    if (!values) return;
    setLoading(true);
    setTimeout(() => {
      setData(prev => prev.filter(item => {
        const byTag = values.greenScreenTemplateTagId ? item.tagId === values.greenScreenTemplateTagId : true;
        const byId = values.id ? String(item.id).includes(values.id) : true;
        const byName = values.name ? item.name.includes(values.name) : true;
        const byCreateBy = values.createBy ? item.createBy.includes(values.createBy) : true;
        return byTag && byId && byName && byCreateBy;
      }));
      setLoading(false);
    }, 300);
  };

  const resetSearch = () => {
    form.resetFields();
    setData(Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      name: `绿幕-${i + 1}`,
      createBy: i % 2 === 0 ? 'admin' : 'designer',
      tagId: i % 3 === 0 ? 1 : 2,
      tagName: i % 3 === 0 ? '人物' : '风景',
      amount: Math.floor(Math.random() * 50) + 20,
      image: `https://picsum.photos/seed/green_${i}/240/160`,
      createTime: `2025-03-${(i % 28) + 1} 09:00:00`,
    })));
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const handleDelete = (row) => {
    Modal.confirm({
      title: '删除绿幕模板',
      content: `将删除绿幕模板 ${row.name}（ID: ${row.id}）`,
      onOk: () => {
        setData(prev => prev.filter(d => d.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const handleEdit = (row) => {
    setCurrentRow(row);
    setEditOpen(true);
  };

  const beforeUploadToBase64 = async (file, callback) => {
    const reader = new FileReader();
    reader.onload = () => callback(reader.result);
    reader.readAsDataURL(file);
  };

  const handleNewSubmit = () => {
    const formId = 'green-new-form';
    const formEl = document.getElementById(formId);
    if (!formEl) return;
    const values = Object.fromEntries(new FormData(formEl).entries());
    const newId = Math.max(...data.map(d => d.id)) + 1;
    const tag = tags.find(t => String(t.id) === values.greenScreenTemplateTagId);
    setData(prev => [{
      id: newId,
      name: values.name || `新绿幕-${newId}`,
      createBy: 'admin',
      tagId: tag?.id,
      tagName: tag?.name || '-',
      amount: values.amount ? Number(values.amount) : 0,
      image: values.image || `https://picsum.photos/seed/green_${newId}/240/160`,
      createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    }, ...prev]);
    setNewOpen(false);
    message.success('新增绿幕模板成功');
  };

  return (
    <div style={{ padding: 16 }}>
      <Card
        title={<Space><BgColorsOutlined />玩法管理 - 绿幕模板</Space>}
        extra={(
          <Space>
            <Button type="primary" icon={<TagsOutlined />} onClick={() => setTagOpen(true)}>标签管理</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setNewOpen(true)}>新增绿幕</Button>
          </Space>
        )}
        style={{ marginBottom: 16 }}
      >
        <Form layout="inline" form={form} style={{ rowGap: 12 }}>
          <Form.Item name="greenScreenTemplateTagId" label="模板标签">
            <Select allowClear placeholder="请选择" style={{ width: 160 }}>
              {tags.map(t => (<Option key={t.id} value={t.id}>{t.name}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item name="id" label="ID">
            <Input placeholder="模板ID" allowClear style={{ width: 140 }} />
          </Form.Item>
          <Form.Item name="name" label="名称">
            <Input placeholder="模板名称" allowClear style={{ width: 180 }} />
          </Form.Item>
          <Form.Item name="createBy" label="创建者">
            <Input placeholder="创建者" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="dateRange" label="创建时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>查询</Button>
              <Button onClick={resetSearch}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增绿幕 */}
      <Modal
        title="新增绿幕模板"
        open={newOpen}
        onCancel={() => setNewOpen(false)}
        onOk={handleNewSubmit}
        destroyOnClose
        width={720}
      >
        <form id="green-new-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space>
              <Input name="name" placeholder="模板名称" style={{ width: 240 }} />
              <InputNumber name="amount" placeholder="价格" style={{ width: 160 }} min={0} />
            </Space>
            <Space>
              <Select name="greenScreenTemplateTagId" placeholder="模板标签" style={{ width: 240 }}>
                {tags.map(t => (<Option key={t.id} value={String(t.id)}>{t.name}</Option>))}
              </Select>
            </Space>
            <Space>
              <Upload
                accept=".png,.jpg,.jpeg,.webp"
                beforeUpload={(file) => { beforeUploadToBase64(file, (url) => {
                  const input = document.querySelector('input[name="image"]');
                  if (input) input.value = url;
                  message.success('绿幕图已选择');
                }); return false; }}
              >
                <Button>选择绿幕图</Button>
              </Upload>
            </Space>
            <Input type="hidden" name="image" />
          </Space>
        </form>
      </Modal>

      {/* 编辑 */}
      <Modal
        title="编辑绿幕模板"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={() => {
          const formId = 'green-edit-form';
          const formEl = document.getElementById(formId);
          if (!formEl || !currentRow) return;
          const values = Object.fromEntries(new FormData(formEl).entries());
          setData(prev => prev.map(d => d.id === currentRow.id ? {
            ...d,
            name: values.name || d.name,
            tagId: values.greenScreenTemplateTagId ? Number(values.greenScreenTemplateTagId) : d.tagId,
            tagName: values.greenScreenTemplateTagId ? (tags.find(t => String(t.id) === values.greenScreenTemplateTagId)?.name || d.tagName) : d.tagName,
            amount: values.amount ? Number(values.amount) : d.amount,
            image: values.image || d.image,
          } : d));
          setEditOpen(false);
          message.success('编辑成功');
        }}
        destroyOnClose
        width={720}
      >
        {currentRow && (
          <form id="green-edit-form">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Space>
                <Input name="name" placeholder="模板名称" defaultValue={currentRow.name} style={{ width: 240 }} />
                <InputNumber name="amount" placeholder="价格" defaultValue={currentRow.amount} style={{ width: 160 }} min={0} />
              </Space>
              <Space>
                <Select name="greenScreenTemplateTagId" defaultValue={String(currentRow.tagId)} placeholder="模板标签" style={{ width: 240 }}>
                  {tags.map(t => (<Option key={t.id} value={String(t.id)}>{t.name}</Option>))}
                </Select>
              </Space>
              <Space>
                <Upload
                  accept=".png,.jpg,.jpeg,.webp"
                  beforeUpload={(file) => { beforeUploadToBase64(file, (url) => {
                    const input = document.querySelector('input[name="image"]');
                    if (input) input.value = url;
                    message.success('绿幕图已选择');
                  }); return false; }}
                >
                  <Button>选择绿幕图</Button>
                </Upload>
                <Image src={currentRow.image} width={120} height={80} style={{ objectFit: 'cover' }} />
              </Space>
              <Input type="hidden" name="image" />
            </Space>
          </form>
        )}
      </Modal>
    </div>
  );
}